package com.example.androiddemo;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

public class Lesson5_2Activity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
    private TextView textView;
    private String text = "";
    private boolean[] selectBall = new boolean[]{false,false,false};
    private String[] ballAarry = new String[]{"篮球","足球","乒乓球"};
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lesson5_2);
        /**
         * 1.点击每个复选框，Toast出每个复选框的选中状态(true/false)+复选框的文字内容；(举 例:false+篮球)
         * 2.有一个TextView(无论放在哪)，点击这个TextView会将所有打上勾的复选框的文字内容 显示并以连字符连接。
         *  （举例:下图应该显示内容为“篮球-乒乓球”）
         * */
        textView = (TextView) findViewById(R.id.result_text);
        // 为CheckBox绑定监听器
        ((CheckBox) findViewById(R.id.basketball)).setOnCheckedChangeListener(this);
        ((CheckBox) findViewById(R.id.football)).setOnCheckedChangeListener(this);
        ((CheckBox) findViewById(R.id.ping)).setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        switch (compoundButton.getId()){
            case R.id.basketball:
                selectBall[0] = b;
                text = selectBall[0] + ballAarry[0];
                Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
                break;
            case R.id.football:
                selectBall[1] = b;
                text = selectBall[1] + ballAarry[1];
                Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
                break;
            case R.id.ping:
                selectBall[2] = b;
                text = selectBall[2] + ballAarry[2];
                Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
                break;
            default:
                return;

        }
        ArrayList<String> selectList = new ArrayList<String>();
        for(int i = 0; i<selectBall.length; i++){
            if(selectBall[i]){
                selectList.add(ballAarry[i]);

            }
        }
        if(selectList.size() != 0){
            String ret = "";
            for(int i = 0;i<selectList.size();i++){
                if(i < selectList.size() -1){
                    // ret + = selectBall[i] +"-" 错误写法
                    ret += selectList.get(i) + "-";
                }else{
                    ret += selectList.get(i);
                }
            }
            textView.setText(ret);
        }else{
            textView.setText("你没有选中任何运动");
        }

    }
}


